# -*- coding:utf-8 -*-
# __author__ : "张百科"
# Date: 2021/1/22 13:59
# File: auth.py
# IDE: PyCharm

from rest_framework.views import APIView
from utils.Decorators.webworkdecorator import WorkDecorator
from rest_framework.schemas import AutoSchema
from django.contrib.auth.hashers import make_password, check_password
from django.contrib.auth.models import User
from models.user import User
from serializers.user import UserSerializer
from utils.response.response import BaseResponse
from utils.response.httpstate import *
from utils import token
from django.middleware import csrf
from rest_framework import status
import datetime
import coreapi

class LoginView(APIView):
    authentication_classes = []  # 重写父类的属性,当前视图不需要token权限验证
    permission_classes = []
    schema = AutoSchema(manual_fields=[
        coreapi.Field(name='username', required=True, location='form', description='用户登录名', ),
        coreapi.Field(name='password', required=True, location='form', description='用户登录密码', ),
    ])

    @WorkDecorator(operate="用户",message='登录')
    def post(self,request,*args,**kwargs):
        try:
            # postData = json.loads(request.body)
            postData = request.data
            loginname = postData['username']
            password = postData['password']

            if len(loginname) > 0 and len(password) > 0:
                # 根据名称获取用户信息
                cur_user = User.objects.filter(login_name=loginname, is_delete=0,is_allowed_login=1).first()
                if cur_user:
                    if check_password(password, cur_user.password):
                        result = UserSerializer(cur_user)
                        cur_user.token = token.Tokens.set_token(self, result.data)
                        cur_user.last_login_time = datetime.datetime.now()
                        cur_user.login_count += 1
                        cur_user.save()
                        result = UserSerializer(cur_user)

                        return BaseResponse(data=result.data)
                    else:

                        return BaseResponse(message='登录名或密码不正确', code=CODE_BUSSINESS_ERROR)
                else:
                    return BaseResponse(message='用户账号不存在或已停用', code=CODE_BUSSINESS_ERROR)
            else:
                return BaseResponse(message='用户名或者密码为空', code=CODE_BUSSINESS_ERROR, status=status.HTTP_400_BAD_REQUEST)
        except Exception as ex:
            return BaseResponse(message=str(ex), code=CODE_BUSSINESS_ERROR, status=status.HTTP_400_BAD_REQUEST)

    def get(self,request):
        token = csrf.get_token(request)
        return BaseResponse(data={'X-CSRFToken' : token})